// CSE 142 Winter 2008, Marty Stepp // This file describes a new type of objects named Point. // // This second version includes constructors and more methods. public class Point { // fields (data inside each Point object) int x; // each Point object has two ints inside it: int y; // x and y. // constructors (initializes the state of each Point object) // Creates a new Point at the given x/y coordinates. // common bug: writing 'void' return type // common bug: mis-initializing fields (startingX = x; int x = startingX;) public Point(int startingX, int startingY) { x = startingX; y = startingY; } // Creates a new Point at the origin, (0, 0). public Point() { x = 0; y = 0; } // methods (behavior inside each Point object) // Returns the distance between this Point and the given other Point. public double distance(Point p2) { // a^2 + b^2 = c^2 int dx = x - p2.x; int dy = y - p2.y; double d = Math.sqrt(dx*dx + dy*dy); return d; } // Returns the distance between this Point and the origin, (0, 0). public double distanceFromOrigin() { // Point origin = new Point(); // double d = distance(origin); // return d; return distance(new Point()); } // Adjusts this Point object's location by the given amounts. public void translate(int dx, int dy) { // This code runs inside a particular Point object. // (We say the code runs "in the context of" that object.) // The code knows which object that is, // and it knows how to access or change that object's fields. this.x = this.x + dx; // change "this" Point's x this.y = this.y + dy; // change "this" Point's y } }